<template>
	<view>
		<!-- 登录提示弹窗 -->
		<uni-popup ref="loginPopup" type="center" :mask-click="false">
			<view class="popup-content">
				<view class="popup-title">请先登录</view>
				<view class="popup-desc">您需要登录后才能继续操作。</view>
				<button class="popup-btn" @click="handleWeChatLogin">微信登录</button>
			</view>
		</uni-popup>

		<!-- 设置用户信息弹窗 -->
		<uni-popup ref="userInfoPopup" type="center" :mask-click="false">
			<view class="popup-content">
				<view class="popup-title">完善个人信息</view>
				<view class="popup-form">
					<image :src="userInfo.avatar" v-if="userInfo.avatar"
						mode="aspectFill" class="avatar-image" />
					
					<button 
					      open-type="chooseAvatar"
					      @chooseavatar="onChooseAvatar"
					      class="guide-btn" style="margin-bottom: 10px;"
					    >
					      {{userInfo.avatar?'重设头像':'授权头像'}}
					    </button>
					<input class="popup-input" type="text" v-model="userInfo.nickName" placeholder="请输入昵称" />
					<!-- <input class="popup-input" type="text" v-model="userInfo.avatar" placeholder="请输入头像链接" /> -->
					<input class="popup-input" type="number" v-model="userInfo.userName" placeholder="请输入手机号码" />
				</view>
				<button class="popup-btn" @click="saveUserInfo">保存信息</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { commUrl,appID } from '@/config/common';
	import {
		request
	} from '@/utils/api';
	import {
		ref,
		reactive,
		onMounted
	} from "vue";
	import {
		mainStore
	} from '@/store/index.js';
	const emit = defineEmits(['success'])
	// 数据模型
	const userInfo = reactive({
		nickName: "",
		avatar: "",
		userName: "",
	});
	const isLoggedIn = ref(false);

	// 引用弹窗组件
	const loginPopup = ref(null);
	const userInfoPopup = ref(null);

	// 检查用户是否已登录
	const checkLoginStatus = () => {
		const storedUserInfo = uni.getStorageSync("userInfo");
		if (!storedUserInfo || !storedUserInfo.isLoggedIn) {
			 // 弹出登录提示
		} else {
			Object.assign(userInfo, storedUserInfo); // 更新用户信息
			isLoggedIn.value = true;
		}
	};

	// 处理微信登录
	const handleWeChatLogin = async () => {
		try {
			let code = await mainStore().login()
			let data = {
				code,
				appID:appID
			}
			let res =  await request({
				url: '/sanitation/v1/login',
				method: 'POST',
				data
			})
		
			uni.setStorageSync('token',res.token);
			mainStore().token = res.token
			await mainStore().setUserInfo({nickName:res.nickName??''})
			
			await mainStore().getUserInfo()
			const storedUserInfo = mainStore().userInfo;
			userInfo.nickName = storedUserInfo.nickName??'';
			userInfo.avatar = storedUserInfo.avatar??'';
			userInfo.userName = storedUserInfo.userName??'';
			if (!storedUserInfo.nickName || !storedUserInfo.avatar || !storedUserInfo.userName) {
				userInfoPopup.value.open(); // 弹出完善信息的弹窗
			} else {
				isLoggedIn.value = true; // 已登录且信息完整
				loginPopup.value.close();
				uni.showTabBar({animation: false})
			}
		} catch (e) {
			
			console.log(e)
		}
	};
	
	const onChooseAvatar = (e)=> {
		userInfo.avatar = e.detail.avatarUrl
	}
	// 保存用户信息
	const saveUserInfo = () => {
		if (!userInfo.nickName || !userInfo.avatar || !userInfo.userName) {
			uni.showToast({
				title: "请填写完整信息",
				icon: "none",
			});
			return;
		}
		if(userInfo.nickName.length>32){
			uni.showToast({
				title: "昵称最长32个字符",
				icon: "none",
			});
			return
		}
		const phoneNumberRegex = /^1[3-9]\d{9}$/;
		if(userInfo.userName&&!phoneNumberRegex.test(userInfo.userName)){
			uni.showToast({
				title: "请输入有效的手机号码",
				icon: "none",
			});
			return
			
		}
		
		// // 保存用户信息到本地存储
		// const updatedUserInfo = {
		// 	isLoggedIn: true,
		// 	...userInfo,
		// };
		// uni.setStorageSync("userInfo", updatedUserInfo);
		try{	
			mainStore().updateUserInfo(userInfo)
			// 关闭弹窗并更新登录状态
			isLoggedIn.value = true;
			uni.showTabBar({animation: false})
			userInfoPopup.value.close();
			uni.showToast({
				title: "信息保存成功",
				icon: "none",
			});
			emit('success')
		}
		catch(e){
			
		}
	};
	/**
	 * @param type {number}  1:未登录|2登录了 没有设置个人信息
	 */
	const open = (type) => {
		uni.hideTabBar({animation: false})
		if(type==1){
			loginPopup.value.open();
		}
		else{
			const UserInfo = mainStore().userInfo;
			userInfo.nickName = UserInfo.nickName??'';
			userInfo.avatar = UserInfo.avatar??'';
			userInfo.userName = UserInfo.userName??'';
			userInfoPopup.value.open();
		}
		
	}
	
	defineExpose({
		open
	})
</script>

<style scoped>
.popup-content {
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;
  text-align: center;
}
.popup-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
.popup-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}
.popup-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  /* padding: 10px 20px; */
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  height: 45px;
  line-height: 45px;
  margin-top: 25px;
}
.popup-input {
  width: calc(100% - 20px);
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0 10px;
  margin-bottom: 10px;
}


.avatar-image {
  width: 45px;
  height: 45px;
  margin-bottom: 10px;
}
.avatar-placeholder {
  font-size: 14px;
  color: #999;
}
</style>